package com.penngo.gui.dfdiff.view;

import cn.hutool.core.io.FileUtil;
import com.penngo.gui.dfdiff.utils.GB;
import javax.swing.*;
import java.awt.*;
import java.io.File;

public class RightTabbed extends JPanel {
    private TabbedPaneClose tabbedPane = null;
    public RightTabbed() {
        setLayout(new GridBagLayout());
        tabbedPane = new TabbedPaneClose();
        tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        this.add(tabbedPane, new GB(0,0,1,1).setFill(GB.BOTH).setWeight(100,100));
    }
    public void addTab(String title, String toolTip, Component comp) {
        tabbedPane.addTab(title, toolTip, comp);
    }

    public void setSelect(Component comp) {
        Component[] components = tabbedPane.getComponents();
        for(int i = 0; i < components.length; i++) {
            if(components[i] == comp) {
                tabbedPane.setSelectedComponent(components[i]);
                break;
            }
        }
    }
    public void setSelect(ProjectNode node, String title) {
        int count = tabbedPane.getTabCount();
        for(int i = 0; i < count; i++) {
            if(tabbedPane.getComponentAt(i) instanceof RightPanel rightPanel){
                if (node.equals(rightPanel.getProjectNode())){
                    tabbedPane.setTitle(title, rightPanel);
                    tabbedPane.setSelectedComponent(rightPanel);
                }
            }
//            if(components[i] == comp) {
//                tabbedPane.setSelectedComponent(components[i]);
//                break;
//            }
        }
    }
    public void removeTab(ProjectNode node) {
        int tabCount = tabbedPane.getTabCount();
        for(int i = 0; i < tabCount; i++){
            if (tabbedPane.getComponentAt(i) instanceof RightPanel rightPanel){
                if (node.equals(rightPanel.getProjectNode())){
                    tabbedPane.removeTabAt(i);
                }
            }
        }
    }
    public Component getSelectedTab() {
        return tabbedPane.getSelectedComponent();
    }

    public Component[] getAllComponent(){
        return tabbedPane.getComponents();
    }

    public void setTitle(String title, Component component){
        tabbedPane.setTitle(title, component);
    }

    public void save(){
        int count = tabbedPane.getTabCount();
        for(int i = 0; i < count; i++){
            Component com = tabbedPane.getTabComponentAt(i);
            if(com instanceof RightEditor rightEditor){
                ProjectNode node = rightEditor.getProjectNode();
                File curFile = node.getPathLeft();
                if(curFile != null && curFile.exists()){
                    FileUtil.writeString(rightEditor.getEditor().getText(), curFile, "UTF-8");
                }
            }
        }
    }
}
